<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="800">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="80px"
    >
      <el-form-item label="上级部门" prop="parentId">
        <el-tree-select
          v-model="formData.parentId"
          :data="deptTree"
          :props="{ ...defaultProps, label: 'name2' }"
          check-strictly
          default-expand-all
          placeholder="请选择上级部门"
        />
        <!--          <el-tree-select-->
        <!--            v-model="formData.parentId"-->
        <!--            :data="deptTree"-->
        <!--            :props="defaultProps"-->
        <!--            check-strictly-->
        <!--            default-expand-all-->
        <!--            placeholder="请选择上级部门"-->
        <!--          >-->
        <!--          <template #default="{ data: { name, status } }">-->
        <!--            {{ name }} {{ status === EnableStatusEnum.Disabled ? `[${disable_status_label}]` : '' }}-->
        <!--          </template>-->
        <!--          <template #default="scope">-->
        <!--            {{ scope.data.parentId ?? '' }}-->
        <!--          </template>-->
        <!--        </el-tree-select>-->
      </el-form-item>
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入部门名称" />
      </el-form-item>
      <el-form-item label="显示排序" prop="sort">
        <el-input-number v-model="formData.sort" controls-position="right" />
      </el-form-item>
      <el-form-item label="负责人" prop="leaderId">
        <el-select v-model="formData.leaderId" clearable placeholder="请输入负责人">
          <el-option
            v-for="item in staffList"
            :key="item.staffId!"
            :label="item.nickname"
            :value="item.staffId!"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="联系电话" prop="phone">
        <el-input v-model="formData.phone" maxlength="11" placeholder="请输入联系电话" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="formData.email" maxlength="50" placeholder="请输入邮箱" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio v-for="dict in common_enable_status" :key="dict.value" :value="dict.value">
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import * as DeptApi from '@/api/system/dept'
import * as StaffApi from '@/api/system/staff'
import type { FormRules } from 'element-plus'
import { EnableStatusEnum } from '@/utils/constants'
import { defaultProps, handleTree } from '@/utils/tree'

defineOptions({ name: 'SystemDeptForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const { common_enable_status } = useIntDict(DICT_TYPE.common_enable_status)
const disable_status_label = getDictLabel(DICT_TYPE.common_enable_status, EnableStatusEnum.Disabled)

const dialogVisible = ref(false) // dialog是否展示
const dialogTitle = ref('') // dialog标题
const formLoading = ref(false) // 表单加载中标记，1. 修改时的数据加载，2. 提交的按钮禁用
const formType = ref('') // 表单类型，新增：create，修改：update
const formData = ref({
  id: undefined,
  name: '',
  parentId: undefined as any,
  leaderId: '',
  phone: '',
  email: '',
  status: EnableStatusEnum.Enabled,
  sort: 0
})
const formRules = reactive<FormRules>({
  parentId: [{ required: true, message: '上级部门不能为空', trigger: 'blur' }],
  name: [{ required: true, message: '部门名称不能为空', trigger: 'blur' }],
  email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }],
  phone: [
    { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  sort: [{ required: true, message: '显示顺序不能为空', trigger: 'blur' }]
})

const staffList = ref<StaffApi.StaffVO[]>([]) // 用户列表

const formRef = ref() // 表单ref

const open = async (type: string, id?: number, parentId?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  if (parentId) {
    formData.value.parentId = parentId
  }
  if (id) {
    formLoading.value = true
    try {
      formData.value = await DeptApi.getDept(id)
    } finally {
      formLoading.value = false
    }
  }
  // 获取用户列表
  staffList.value = await StaffApi.getStaffSimpleList()
  // 获取部门树
  await getDeptTree()
}

defineExpose({ open })

const emit = defineEmits(['success']) // 定义success事件，用于操作成功后的回调
const submitForm = async () => {
  if (await formValidate(formRef)) return
  formLoading.value = true
  try {
    if (formType.value === 'create') {
      await DeptApi.createDept(formData.value)
      message.success(t('common.createSuccess'))
    } else {
      await DeptApi.updateDept(formData.value)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const resetForm = () => {
  formData.value = {
    id: undefined,
    name: '',
    parentId: undefined,
    leaderId: '',
    phone: '',
    email: '',
    status: EnableStatusEnum.Enabled,
    sort: 0
  }
  formRef.value?.resetFields()
}

const deptTree = ref() // 树形结构
// 获取部门树
const getDeptTree = async () => {
  deptTree.value = []
  const data = await DeptApi.getDeptSimpleList()
  const dept: Tree & { name2: string } = {
    id: 0,
    name: '顶级部门',
    name2: '顶级部门',
    children: []
  }
  data.forEach((item) => {
    item.name2 =
      item.name + (item.status === EnableStatusEnum.Enabled ? '' : ` [${disable_status_label}]`)
  })
  dept.children = handleTree(data)
  deptTree.value.push(dept)
}
</script>

<style scoped lang="scss"></style>
